import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import {
  Row,
  Col,
  Card,
  Button,
  Tag,
  Tabs,
  Rate,
  Descriptions,
  List,
  Avatar,
  Progress,
  Space,
  message,
  Modal,
  Tooltip,
  Statistic,
  Empty,
  Result
} from 'antd';
import {
  UserOutlined,
  ClockCircleOutlined,
  BookOutlined,
  DollarOutlined,
  PlayCircleOutlined,
  FileTextOutlined,
  TeamOutlined,
  StarOutlined,
  CloseOutlined,
  CheckCircleOutlined,
  EyeOutlined
} from '@ant-design/icons';
import { setCurrentCourse, setLoading } from '../../store/courseSlice';
import ReactPlayer from 'react-player';
import { calculateAndUpdateCourseProgress } from '../../store/learningSlice';
import { courseApi } from '../../api/courseApi';
import { initialCourses } from '../../store/courseSlice';

const CourseDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { currentCourse } = useSelector(state => state.course);
  const learningProgress = useSelector(state => state.learning.progress[id] || {});
  const [playing, setPlaying] = useState(false);
  const [currentVideo, setCurrentVideo] = useState(null);
  const [isModalVisible, setIsModalVisible] = useState(false);

  useEffect(() => {
    // 将 URL 参数中的 id 转换为数字类型
    const courseId = parseInt(id, 10);

    // 直接从 initialCourses 中查找课程
    const course = initialCourses.find(c => c.id === courseId);
    if (course) {
      dispatch(setCurrentCourse(course));
    } else {
      // 如果找不到课程，显示错误页面
      dispatch(setCurrentCourse(null));
    }
  }, [id, dispatch]);

  useEffect(() => {
    if (id) {
      dispatch(calculateAndUpdateCourseProgress(id));
    }
  }, [id, dispatch]);

  // 如果找不到课程，显示友好的错误页面
  if (!currentCourse) {
    return (
      <Result
        status="404"
        title="课程不存在"
        subTitle="抱歉，您访问的课程不存在或已被删除"
        extra={
          <Button type="primary" onClick={() => navigate('/courses')}>
            返回课程列表
          </Button>
        }
      />
    );
  }

  // 课程评价数据（模拟）
  const reviews = [
    {
      user: '张三',
      avatar: 'https://via.placeholder.com/40',
      rating: 5,
      comment: '课程内容非常详细，讲解清晰，收获很大！',
      date: '2024-03-15'
    },
    {
      user: '李四',
      avatar: 'https://via.placeholder.com/40',
      rating: 4,
      comment: '整体不错，但是有些地方可以讲得更详细一些。',
      date: '2024-03-14'
    }
  ];

  const handlePlayCourse = () => {
    // 默认播放第一个章节
    const firstChapter = currentCourse?.chapters?.[0];
    if (firstChapter) {
      setCurrentVideo({
        title: firstChapter.title,
        duration: formatDuration(firstChapter.duration),
        videoUrl: `https://example.com/videos/${currentCourse.id}/${firstChapter.id}.mp4`
      });
      setIsModalVisible(true);
      setPlaying(true);
    } else {
      message.info('课程暂无内容');
    }
  };

  const handlePlayLesson = (chapter) => {
    setCurrentVideo({
      title: chapter.title,
      duration: formatDuration(chapter.duration),
      videoUrl: `https://example.com/videos/${currentCourse.id}/${chapter.id}.mp4`
    });
    setIsModalVisible(true);
    setPlaying(true);
  };

  // 添加格式化时长的辅助函数
  const formatDuration = (seconds) => {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    return hours > 0 ? `${hours}小时${minutes}分钟` : `${minutes}分钟`;
  };

  // 计算总体学习进度
  const calculateOverallProgress = () => {
    if (!currentCourse?.chapters?.length) return 0;
    const completedChapters = currentCourse.chapters.filter(
      chapter => learningProgress[chapter.id]?.completed
    ).length;
    return Math.round((completedChapters / currentCourse.chapters.length) * 100);
  };

  // 计算总学习时长
  const calculateTotalLearningTime = () => {
    if (!currentCourse?.chapters) return 0;
    return Object.values(learningProgress).reduce((total, progress) => {
      return total + (progress.videoPosition || 0);
    }, 0);
  };

  // 格式化学习时长
  const formatLearningTime = (seconds) => {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    return hours > 0 ? `${hours}小时${minutes}分钟` : `${minutes}分钟`;
  };

  const items = [
    {
      key: 'overview',
      label: '课程概述',
      children: (
        <div>
          <Descriptions column={1}>
            <Descriptions.Item label="课程简介">
              {currentCourse.description}
            </Descriptions.Item>
            <Descriptions.Item label="适用人群">
              {currentCourse.level}水平的学习者
            </Descriptions.Item>
            <Descriptions.Item label="学习目标">
              <ul>
                {currentCourse?.chapters?.map((chapter, index) => (
                  <li key={chapter.id}>{chapter.description}</li>
                ))}
              </ul>
            </Descriptions.Item>
          </Descriptions>
        </div>
      )
    },
    {
      key: 'chapters',
      label: '课程大纲',
      children: (
        <List
          dataSource={currentCourse?.chapters || []}
          renderItem={(chapter, index) => (
            <List.Item
              actions={[
                <Button
                  type="link"
                  icon={<PlayCircleOutlined />}
                  onClick={() => handlePlayLesson(chapter)}
                >
                  {formatDuration(chapter.duration)}
                </Button>
              ]}
            >
              <List.Item.Meta
                avatar={<FileTextOutlined />}
                title={
                  <Space>
                    {chapter.title}
                    {index === 0 && <Tag color="green">免费试看</Tag>}
                  </Space>
                }
                description={chapter.description}
              />
            </List.Item>
          )}
        />
      )
    },
    {
      key: 'reviews',
      label: '学员评价',
      children: (
        <div>
          <Card style={{ marginBottom: 24 }}>
            <Row gutter={24} align="middle">
              <Col span={8} style={{ textAlign: 'center' }}>
                <div style={{ fontSize: 36, color: '#1890ff' }}>
                  {currentCourse.rating}
                </div>
                <Rate disabled defaultValue={currentCourse.rating} />
                <div>综合评分</div>
              </Col>
              <Col span={16}>
                <div>
                  <Progress percent={85} size="small" format={() => '5星'} />
                  <Progress percent={10} size="small" format={() => '4星'} />
                  <Progress percent={3} size="small" format={() => '3星'} />
                  <Progress percent={1} size="small" format={() => '2星'} />
                  <Progress percent={1} size="small" format={() => '1星'} />
                </div>
              </Col>
            </Row>
          </Card>
          <List
            dataSource={reviews}
            renderItem={review => (
              <List.Item>
                <List.Item.Meta
                  avatar={<Avatar src={review.avatar} />}
                  title={
                    <Space>
                      {review.user}
                      <Rate disabled defaultValue={review.rating} />
                      <span style={{ color: '#999' }}>{review.date}</span>
                    </Space>
                  }
                  description={review.comment}
                />
              </List.Item>
            )}
          />
        </div>
      )
    }
  ];

  const renderProgressOverview = () => (
    <div className="progress-overview">
      <div className="progress-card">
        <Tooltip title="课程总进度">
          <Progress
            type="circle"
            percent={calculateOverallProgress()}
            format={percent => `${percent}%`}
          />
        </Tooltip>
        <div style={{ marginTop: 16, textAlign: 'center' }}>
          课程完成度
        </div>
      </div>
      <div className="progress-card">
        <Statistic
          title="已学习时长"
          value={formatLearningTime(calculateTotalLearningTime())}
          prefix={<ClockCircleOutlined />}
        />
      </div>
      <div className="progress-card">
        <Statistic
          title="已完成章节"
          value={`${currentCourse?.chapters?.filter(ch => learningProgress[ch.id]?.completed).length || 0}/${currentCourse?.chapters?.length || 0}`}
          prefix={<CheckCircleOutlined />}
        />
      </div>
    </div>
  );

  const renderChapterList = () => (
    <div className="chapter-progress-list">
      {currentCourse?.chapters?.map(chapter => {
        const progress = learningProgress[chapter.id] || {};
        const percent = progress.completed ? 100 :
          progress.videoPosition ? Math.round((progress.videoPosition / chapter.duration) * 100) : 0;

        return (
          <div key={chapter.id} className="chapter-progress-item">
            <div className="chapter-progress-header">
              <div className="chapter-progress-title">
                {chapter.title}
                {progress.completed && (
                  <Tag color="success" icon={<CheckCircleOutlined />}>已完成</Tag>
                )}
              </div>
              <Button
                type="primary"
                icon={chapter.type === 'video' ? <PlayCircleOutlined /> : <FileTextOutlined />}
                onClick={() => navigate(`/learning/${id}/${chapter.id}`)}
              >
                {progress.completed ? '复习' : percent > 0 ? '继续学习' : '开始学习'}
              </Button>
            </div>
            <div className="chapter-progress-content">
              <div className="chapter-progress-bar">
                <Progress
                  percent={percent}
                  size="small"
                  status={progress.completed ? "success" : "active"}
                />
              </div>
              <div className="chapter-progress-actions">
                <Button
                  type="link"
                  icon={<PlayCircleOutlined />}
                  onClick={() => handlePlayLesson(chapter)}
                >
                  {formatDuration(chapter.duration)}
                </Button>
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );

  return (
    <div className="course-detail-container">
      <div className="course-header">
        <h1>{currentCourse.title}</h1>
        <div className="course-meta">
          <Space>
            <UserOutlined />
            讲师：{currentCourse.instructor}
          </Space>
          <Space>
            <ClockCircleOutlined />
            课程时长：{currentCourse.duration}
          </Space>
          <Space>
            <TeamOutlined />
            已报名：{currentCourse.enrollments}人
          </Space>
          <Space>
            <StarOutlined />
            评分：{currentCourse.rating}
          </Space>
        </div>
        <div className="course-description">
          {currentCourse.description}
        </div>
      </div>

      <div className="course-content">
        <div className="course-main">
          <div className="video-player-container">
            <ReactPlayer
              url={currentVideo?.videoUrl || `https://example.com/videos/${currentCourse.id}/${currentCourse.chapters?.[0]?.id}.mp4`}
              playing={playing}
              controls={true}
              width="100%"
              height="450px"
              className="video-player"
              light={currentCourse.coverImage}
              playIcon={
                <div className="video-play-icon">
                  <PlayCircleOutlined style={{ fontSize: 64, color: '#fff' }} />
                </div>
              }
            />
            <div className="video-info">
              <h3>{currentVideo?.title || currentCourse.chapters?.[0]?.title || '课程视频'}</h3>
              <div className="video-meta">
                <Space>
                  <ClockCircleOutlined />
                  <span>时长: {currentVideo?.duration || formatDuration(currentCourse.chapters?.[0]?.duration)}</span>
                </Space>
                <Space>
                  <EyeOutlined />
                  <span>播放次数: {currentVideo?.views || 0}</span>
                </Space>
              </div>
            </div>
          </div>

          <Tabs items={items} />

          <div className="learning-progress-section">
            <h2>学习进度</h2>
            {renderProgressOverview()}
            {renderChapterList()}
          </div>
        </div>

        <div className="course-sidebar">
          <div className="enroll-card">
            <div className="enroll-price">
              <DollarOutlined /> {currentCourse.price}
            </div>
            <Button
              type="primary"
              icon={<BookOutlined />}
              size="large"
              block
              className="enroll-button"
              onClick={() => message.success('报名成功！')}
            >
              立即报名
            </Button>
            <div>
              <h3>课程包含</h3>
              <ul className="course-features">
                <li><ClockCircleOutlined /> {currentCourse.duration}课程时长</li>
                <li><FileTextOutlined /> 随堂练习和作业</li>
                <li><BookOutlined /> 终身学习权限</li>
                <li><UserOutlined /> 讲师答疑服务</li>
              </ul>
            </div>
          </div>
        </div>
      </div>

      {/* 视频播放模态框 */}
      <Modal
        title={
          <div className="video-modal-title">
            <PlayCircleOutlined style={{ marginRight: 8 }} />
            {currentVideo?.title || '视频播放'}
          </div>
        }
        visible={isModalVisible}
        onCancel={() => {
          setIsModalVisible(false);
          setPlaying(false);
        }}
        footer={null}
        width={800}
        closeIcon={<CloseOutlined />}
        destroyOnClose
        className="video-modal"
      >
        {currentVideo && (
          <div className="video-player-container">
            <ReactPlayer
              url={currentVideo.videoUrl}
              playing={playing}
              controls={true}
              width="100%"
              height="450px"
              className="video-player"
              light={currentCourse.coverImage}
              playIcon={
                <div className="video-play-icon">
                  <PlayCircleOutlined style={{ fontSize: 64, color: '#fff' }} />
                </div>
              }
            />
            <div className="video-info">
              <h3>{currentVideo.title}</h3>
              <div className="video-meta">
                <Space>
                  <ClockCircleOutlined />
                  <span>时长: {currentVideo.duration}</span>
                </Space>
                <Space>
                  <EyeOutlined />
                  <span>播放次数: {currentVideo.views || 0}</span>
                </Space>
              </div>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default CourseDetail;